/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.terramagnet.mvcframework.asynchronous.jdbc;

import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.terramagnet.mvcframework.asynchronous.PersistentAsynchrony;

/**
 * 异步数据库操作. 单线程队列处理数据库操作。
 *
 * @author lip
 */
@Service
public class AsyncDao extends PersistentAsynchrony<Update> {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    protected void take(Update sql) {
        if (sql.isBatched()) {
            jdbcTemplate.batchUpdate(sql.getSql(), sql.getBatch());
        } else if (sql.isMultiple()) {
            jdbcTemplate.batchUpdate(sql.getSql(), sql.toArgs());
        } else {
            jdbcTemplate.update(sql.getSql(), sql.toArgs().get(0));
        }
    }

    /**
     * 异步批量执行SQL语句.
     */
    public void update(String sql, List<Serializable[]> parameters) {
        Update update = new Update(sql);
        for (Serializable[] params : parameters) {
            update.add(params);
        }
        put(update);
    }

    /**
     * 异步批量更新数据库.
     *
     * @param sql sql语句
     * @param batchPreparedStatementSetter 该对象必须实现{@link Serializable 序列化}接口，否则无法在系统关闭时保存数据。
     */
    public void update(String sql, BatchPreparedStatementSetter batchPreparedStatementSetter) {
        Update update = new Update(sql);
        update.setBatch(batchPreparedStatementSetter);
        put(update);
    }

    /**
     * 异步更新数据库.
     */
    public void update(String sql, Serializable... parameters) {
        put(new Update(sql).add(parameters));
    }

}
